package com.hdu.dwh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hdu.dwh.mapper.DatabaseAllMapper;
import com.hdu.dwh.pojos.DatabaseAll;
import com.hdu.dwh.pojos.SubjectTable;
import com.hdu.dwh.pojos.source_access_pojos.DataWarehouseTable;
import com.hdu.dwh.service.IDatabaseAllService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdu.dwh.vos.TableDetilVo;
import com.hdu.dwh.constants.CommonConstants;
import com.hdu.dwh.constants.ParamConstants;
import com.hdu.dwh.results.ResponseResult;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 统一数据库表 服务实现类
 * </p>
 *
 * @author bobo
 * @since 2025-04-10
 */
@Service
public class DatabaseAllServiceImpl extends ServiceImpl<DatabaseAllMapper, DatabaseAll> implements IDatabaseAllService {

    /**
     * 判断数据库是否存在
     * @param sourceDatabaseName
     * @return
     */
    @Override
    public boolean existsDatabase(String sourceDatabaseName) {
        LambdaQueryWrapper<DatabaseAll> queryWrapper = new LambdaQueryWrapper<DatabaseAll>()
                .eq(DatabaseAll::getDatabaseName, sourceDatabaseName);
        return exists(queryWrapper);
    }

    /**
     * 创建表详情列表 主要是追加数据库名 从源表
     * @param records
     * @return
     */
    @Override
    public List<TableDetilVo> createTableDetilVoListForSource(List<DataWarehouseTable> records) {
        // 追加数据库名 先获取所有数据库id
        List<Long> databaseIds = records.stream()
                .map(DataWarehouseTable::getDatabaseId)
                .distinct()
                .toList();
        LambdaQueryWrapper<DatabaseAll> queryWrapper = new LambdaQueryWrapper<DatabaseAll>()
                .eq(DatabaseAll::getDatabaseType, ParamConstants.SOURCE_DATABASE)
                .in(DatabaseAll::getDatabaseId, databaseIds);
        List<DatabaseAll> sourceDatabases = list(queryWrapper);
        // 将数据库名映射到一个 Map 中，方便后续查找
        Map<Long, String> databaseNameMap = sourceDatabases.stream()
                .collect(Collectors.toMap(DatabaseAll::getDatabaseId, DatabaseAll::getDatabaseName));
        // 构造返回
        List<TableDetilVo> tableDetilVos = records.stream().map(entity -> {
            TableDetilVo vo = new TableDetilVo();
            BeanUtils.copyProperties(entity, vo);
            // 设置数据库名
            vo.setDatabaseName(databaseNameMap.get(entity.getDatabaseId()));
            return vo;
        }).toList();
        return tableDetilVos;
    }


    /**
     * 创建表详情列表 主要是追加数据库名 从主题表
     * @param records
     * @return
     */
    @Override
    public List<TableDetilVo> createTableDetilVoListForSubject(List<SubjectTable> records) {
        // 追加数据库名 先获取所有数据库id
        List<Long> databaseIds = records.stream()
                .map(SubjectTable::getDatabaseId)
                .distinct()
                .toList();
        LambdaQueryWrapper<DatabaseAll> queryWrapper = new LambdaQueryWrapper<DatabaseAll>()
                .eq(DatabaseAll::getDatabaseType, ParamConstants.SUBJECT_DATABASE)
                .in(DatabaseAll::getDatabaseId, databaseIds);
        List<DatabaseAll> sourceDatabases = list(queryWrapper);
        // 将数据库名映射到一个 Map 中，方便后续查找
        Map<Long, String> databaseNameMap = sourceDatabases.stream()
                .collect(Collectors.toMap(DatabaseAll::getDatabaseId, DatabaseAll::getDatabaseName));
        // 构造返回
        List<TableDetilVo> tableDetilVos = records.stream().map(entity -> {
            TableDetilVo vo = new TableDetilVo();
            BeanUtils.copyProperties(entity, vo);
            // 设置数据库名
            vo.setDatabaseName(databaseNameMap.get(entity.getDatabaseId()));
            return vo;
        }).toList();
        return tableDetilVos;
    }

    /**
     * 查询所有数据库 可根据类型
     * @param dataBaseType
     * @return
     */
    @Override
    public ResponseResult listByDatabaseType(Integer dataBaseType) {
        if(dataBaseType == null){
            List<DatabaseAll> list = list();
            if(list.isEmpty()){
                return ResponseResult.fail(CommonConstants.RECORD_NOT_EXIST);
            }
            return ResponseResult.success(list);
        }
        LambdaQueryWrapper<DatabaseAll> queryWrapper = new LambdaQueryWrapper<DatabaseAll>()
                .eq(DatabaseAll::getDatabaseType, dataBaseType);
        List<DatabaseAll> list = list(queryWrapper);
        if(list.isEmpty()){
            return ResponseResult.fail(CommonConstants.RECORD_NOT_EXIST);
        }
        return ResponseResult.success(list);
    }


    /**
     * 根据数据库名获取数据库id
     * @param databaseName
     * @return
     */
    @Override
    public Long getIdByDatabaseName(String databaseName) {
        LambdaQueryWrapper<DatabaseAll> queryWrapper = new LambdaQueryWrapper<DatabaseAll>()
                .eq(DatabaseAll::getDatabaseName, databaseName);
        DatabaseAll databaseAll = getOne(queryWrapper);
        if(databaseAll == null){
            return null;
        }
        return databaseAll.getDatabaseId();
    }

    /**
     * 判断数据库id是否存在
     * @param databaseId
     * @return
     */
    @Override
    public boolean existsById(Long databaseId) {
        if(databaseId != null){
            LambdaQueryWrapper<DatabaseAll> queryWrapper = new LambdaQueryWrapper<DatabaseAll>()
                    .eq(DatabaseAll::getDatabaseId, databaseId);
            return exists(queryWrapper);
        }
        return false;
    }

    /**
     * 删除数据库
     * @param databaseType
     * @param databaseId
     * @return
     */
    @Override
    public boolean delete(Integer databaseType, Long databaseId) {
        if(databaseId != null){
            LambdaQueryWrapper<DatabaseAll> queryWrapper = new LambdaQueryWrapper<DatabaseAll>()
                    .eq(DatabaseAll::getDatabaseId, databaseId)
                    .eq(DatabaseAll::getDatabaseType, databaseType);
            return remove(queryWrapper);
        }
        return true;
    }
}
